import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';

import 'time_selector_data.dart';

class TimeSelector extends StatefulWidget {

  final List<DayTimeEntity> timeData;

  TimeSelector({@required this.timeData, Key key}) : super(key: key);

  @override
  _State createState() => _State();

}

class _State extends State<TimeSelector> {

  int _daySelected = 0;
  ScrollController _dayScrollController;
  ScrollController _timeScrollController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.timeData == null) {
      throw Exception('time data cannot be null');
    }
    for(int i = 0; i < widget.timeData.length; i++) {
      widget.timeData[i].timeSelectedTemp = widget.timeData[i].timeSelected;
      if(widget.timeData[i].dayIsSelected) {
        _daySelected = i;
      }
    }
    _dayScrollController = ScrollController();
    if(_daySelected > 0) {
      Future.delayed(Duration(milliseconds: 100), (){
        double halfHeight = _dayScrollController.position.viewportDimension / 2;
        double topHalfHeight = ScreenUtil().setWidth(145) * _daySelected + ScreenUtil().setWidth(145) / 2;
        double bottomHalfHeight = ScreenUtil().setWidth(145) * (widget.timeData.length - _daySelected) - ScreenUtil().setWidth(145) / 2;
        if(topHalfHeight > halfHeight && bottomHalfHeight > halfHeight) {
          _dayScrollController.jumpTo(topHalfHeight - halfHeight);
        } else if(bottomHalfHeight <= halfHeight) {
          _dayScrollController.jumpTo(topHalfHeight - (halfHeight * 2 - bottomHalfHeight));
        }
      });
    }
    _timeScrollController = ScrollController();
    if(widget.timeData[_daySelected].timeSelected > 0) {
      Future.delayed(Duration(milliseconds: 100), (){
        double halfHeight = _timeScrollController.position.viewportDimension / 2;
        double topHalfHeight = ScreenUtil().setWidth(145) * widget.timeData[_daySelected].timeSelected + ScreenUtil().setWidth(145) / 2;
        double bottomHalfHeight = ScreenUtil().setWidth(145) *
            (widget.timeData[_daySelected].time.length - widget.timeData[_daySelected].timeSelected) - ScreenUtil().setWidth(145) / 2;
        if(topHalfHeight > halfHeight && bottomHalfHeight > halfHeight) {
          _timeScrollController.jumpTo(topHalfHeight - halfHeight);
        } else if(bottomHalfHeight <= halfHeight) {
          _timeScrollController.jumpTo(topHalfHeight - (halfHeight * 2 - bottomHalfHeight));
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
      children: <Widget>[
        Container(
          padding: EdgeInsets.symmetric(
              vertical: ScreenUtil().setWidth(0)),
          child: Stack(
            alignment: Alignment.centerRight,
            children: <Widget>[
              Center(
                child: Text(
                  '选择时间',
                  style: TextStyle(
                      fontSize: ScreenUtil().setSp(40),
                      color: Colors.grey[900]),
                ),
              ),
              GestureDetector(
                onTap: () => Navigator.of(context).pop(),
                child: Container(
                  padding: EdgeInsets.all(ScreenUtil().setWidth(34)),
                  child: Icon(Icons.close),
                ),
              )
            ],
          ),
        ),
        Divider(
          color: Colors.grey[400],
          height: ScreenUtil().setWidth(1),
        ),
        Padding(
          padding: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
        ),
        Expanded(
          flex: 1,
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  height: double.infinity,
                  color: Colors.grey[200],
                  child: ListView.separated(
                    controller: _dayScrollController,
                      shrinkWrap: true,
                      padding: EdgeInsets.all(0.0),
                      itemBuilder: (context, index) {
                        return GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            setState(() {
                              _daySelected = index;
                            });
                          },
                          child: Container(
                            height: ScreenUtil().setWidth(145),
                            color: _daySelected == index ? Colors.white
                                : Colors.grey[200],
                            child: Center(
                              child: Text(widget.timeData[index].day,
                                  style: TextStyle(
                                      fontSize:
                                      ScreenUtil().setSp(40),
                                      color: _daySelected == index ? Colors.black87
                                          : Colors.grey)),
                            ),
                          ),
                        );
                      },
                      separatorBuilder:
                          (BuildContext context, int index) {
                        return Divider(
                            color: Colors.grey[400],
                            height: ScreenUtil().setWidth(1));
                      },
                      itemCount: widget.timeData.length),
                ),
              ),
              Padding(
                padding:
                EdgeInsets.only(right: ScreenUtil().setWidth(40)),
              ),
              Expanded(
                flex: 2,
                child: ListView.separated(
                  controller: _timeScrollController,
                  itemCount: widget.timeData[_daySelected].time.length,
                  itemBuilder: (BuildContext context, int index) {
                    return GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        setState(() {
                          widget.timeData[_daySelected].timeSelectedTemp = index;
                        });
                        for(int i = 0; i < widget.timeData.length; i++) {
                          if(i != _daySelected) {
                            widget.timeData[i].timeSelectedTemp = -1;
                          }
                        }
                      },
                      child: Container(
                          width: double.infinity,
                          height: ScreenUtil().setWidth(145),
                          padding: EdgeInsets.only(right: ScreenUtil().setWidth(40)),
                          child: Row(
                            children: <Widget>[
                              Expanded(
                                flex: 1,
                                child: Text(widget.timeData[_daySelected].time[index],
                                    style: TextStyle(
                                        color: widget.timeData[_daySelected].timeSelectedTemp == index
                                            ? Colors.blue
                                            : Colors.grey[850],
                                        fontSize:
                                        ScreenUtil().setSp(38))),
                              ),
                              Visibility(
                                visible: widget.timeData[_daySelected].timeSelectedTemp == index,
                                child: Icon(Icons.check, size: ScreenUtil().setWidth(60), color: Colors.blue),
                              )
                            ],
                          )),
                    );
                  },
                  separatorBuilder:
                      (BuildContext context, int index) {
                    return Divider(
                        height: ScreenUtil().setWidth(1),
                        color: Colors.grey[400]);
                  },
                ),
              )
            ],
          ),
        ),
        Container(
          color: Colors.white,
          width: double.infinity,
          padding: EdgeInsets.symmetric(
              horizontal: ScreenUtil().setWidth(40)),
          child: FlatButton(
            onPressed: () {
              widget.timeData.forEach((element) {
                element.dayIsSelected = false;
                element.timeSelected = element.timeSelectedTemp;
              });
              widget.timeData[_daySelected].dayIsSelected = true;
              String time;
              if(widget.timeData[_daySelected].timeSelected == -1) {
                time = '请选择时间';
                widget.timeData.forEach((element) {
                  element.dayIsSelected = false;
                });
                widget.timeData[0].dayIsSelected = true;
                widget.timeData[0].timeSelected = 0;
              } else if(_daySelected == 0 && widget.timeData[_daySelected].timeSelected == 0) {
                time = widget.timeData[_daySelected].time[0];
              } else {
                time = widget.timeData[_daySelected].day + ' '
                    + widget.timeData[_daySelected].time[widget.timeData[_daySelected].timeSelected];
              }
              Navigator.of(context).pop(time);
            },
            child: Text('确定',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: ScreenUtil().setSp(40))),
            color: Colors.blue,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(
                    Radius.circular(ScreenUtil().setWidth(50)))),
          ),
        )
      ],
    );
  }
  
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _dayScrollController.dispose();
    _timeScrollController.dispose();
  }

}